<?php
/**
 * 后台菜单管理控制器
 *
 * @author  web_dxj@163.com
 * @time    2015-09-28 16:41
 */

class Menu extends MY_Controller {

    private $opt = null;

    public function __construct() {
        parent::__construct();

        $this->load->model('menu_model','menu');
        $this->load->model('options_model','options');
        $this->opt = $this->options->get_option($this->menu_option_key);
        if ( ! $this->opt )
        {
            show_error('菜单配置选项不存在');
        }

        $this->menu->initialize( $this->opt->option_value );
    }

    public function index() {
        $data['menu'] = $this->menu
                             ->sort( 'path' , 'asc' )
                             ->handler()
                             ->get_menu();
        $this->load->view('menu/index',$data);
    }


    public function add() {

        $this->load->library('form_validation');
        // 表单的验证配置数组
        $config = array(
            array(
                'field' => 'name',
                'label' => '菜单名称',
                'rules' => 'required',
                'errors' => array(
                    'required' => '%s 不能为空.',
                ),
            ),
        );

        $this->form_validation->set_rules($config);
        if ( FALSE === $this->form_validation->run() )
        {
            ajax_return(self::HTTP_STATUS_FAIL,strip_tags(validation_errors()));
        }


        // Form handler
        $menu['id']     = $this->menu->maxid() + 1;
        $menu['name']   = $this->input->post('name');
        $menu['target'] = $this->input->post('target');
        $menu['url']    = $menu['target'] === 'workspace'
                                           ? site_url($this->input->post('url'))
                                           : $this->input->post('url');
        $menu['icon']   = $this->input->post('icon');
        $parent         = $this->input->post('parent');
        $parent_menu    = $this->menu->find('id',intval($parent));
        if ( is_null($parent_menu) )
        {
            // 如果父级菜单不存在，直接转换为顶级菜单
            // or do some other logic
            $menu['path'] = strval($menu['id']);
        }
        else
        {
            $menu['path'] = $parent_menu['path'] . '-' . $menu['id'];
        }

        // 调用模型添加
        $this->menu->insert_menu( $menu );
        $result = $this->menu->get_menu();

        // Update DB
        if ( FALSE === $this->options->set_option($this->menu_option_key,json_encode($result)) )
        {
            ajax_return(self::HTTP_STATUS_FAIL,'添加菜单失败');
        }

        ajax_return(self::HTTP_STATUS_SUCCESS,'添加菜单成功' . $this->menu->maxid());
    }


    public function edit($id = FALSE) {

        if (empty($id))
        {
            show_error('菜单配置选项不存在');
        }

        $id = intval(hashids_decode($id));

        $edit_menu = $this->menu->find('id',$id);
        if (empty($edit_menu))
        {
            show_error('菜单配置选项不存在');
        }

        // 获取当前菜单的父级菜单
        $path_arr = explode('-',$edit_menu['path']);
        $length   = count($path_arr);

        if ( $length < 2 )
        {
            $parent = 0;
        }
        else
        {
            $parent = $path_arr[$length - 2];
        }

        $data['edit_menu'] = $edit_menu;
        $data['parent']    = intval($parent);
        $data['menu']      = $this->menu->handler()->get_menu();
        $this->load->view('menu/edit', $data);
    }


    public function edit_post() {
        $this->load->library('form_validation');
        // 表单的验证配置数组
        $config = array(
            array(
                'field' => 'name',
                'label' => '菜单名称',
                'rules' => 'required',
                'errors' => array(
                    'required' => '%s 不能为空.',
                ),
            ),
        );

        $this->form_validation->set_rules($config);
        if ( FALSE === $this->form_validation->run() )
        {
            ajax_return(self::HTTP_STATUS_FAIL,strip_tags(validation_errors()));
        }

        // Form handler
        $menu['id']     = intval(hashids_decode($this->input->post('id')));
        $menu['name']   = $this->input->post('name');
        $menu['target'] = $this->input->post('target');
        $menu['url']    = $menu['target'] === 'workspace'
                          ? site_url($this->input->post('url'))
                          : $this->input->post('url');
        $menu['icon']   = $this->input->post('icon');
        $parent         = $this->input->post('parent');
        $parent_menu    = $this->menu->find('id',intval($parent));
        if ( is_null($parent_menu) )
        {
            // 如果父级菜单不存在，直接转换为顶级菜单
            // or do some other logic
            $menu['path'] = strval($menu['id']);
        }
        else
        {
            $menu['path'] = $parent_menu['path'] . '-' . $menu['id'];
        }

        // 调用模型添加
        if ( FALSE === $this->menu->update_menu( $menu ))
        {
            ajax_return(self::HTTP_STATUS_FAIL,'菜单不存在');
        }

        $result = $this->menu->get_menu();
        // Update DB
        if ( FALSE === $this->options->set_option($this->menu_option_key,json_encode($result)) )
        {
            ajax_return(self::HTTP_STATUS_FAIL,'修改失败');
        }

        ajax_return(self::HTTP_STATUS_SUCCESS,'修改成功');

    }


    public function del() {

        $id_arr = explode(',',$this->input->post('id'));
        if (empty($id_arr))
        {
            ajax_return(self::HTTP_STATUS_FAIL,'ID不存在');
        }

        $count = 0;
        foreach ($id_arr as $id)
        {
            if ( TRUE === $this->menu->del_menu(hashids_decode($id)) )
            {
                $count ++ ;
            }
        }

        // Write to DB
        if ( FALSE !== $this->options->set_option($this->menu_option_key,json_encode($this->menu->get_menu())))
        {
            ajax_return(self::HTTP_STATUS_SUCCESS,'删除成功');
        }

        ajax_return(self::HTTP_STATUS_FAIL,'删除失败');
    }

}